<template>
  <div class="comp-add-document">
    <el-drawer :with-header="false" size="50%" :wrapperClosable="false" :modal="false" :visible.sync="isDrawer" :before-close="handleClose(1)">
      <div class="drawer-container">
        <div class="header">
          <div class="title">{{ command == 1 ? "新增文档" : command == 2 ? "批量新增" : command == 3 ? "编辑文档" : "" }}</div>
          <div @click="handleClose" class="close iconfont">&#xe673;</div>
        </div>
        <div class="section">
          <template v-if="command == 2">
            <div class="bar">
              <div class="bar-title"><span class="span"></span>添加文件基本信息</div>
              <el-upload multiple :before-upload="beforeUpload" :http-request="batchUpload" :show-file-list="false" action="https://jsonplaceholder.typicode.com/posts/">
                <el-button type="primary">批量上传</el-button>
              </el-upload>
            </div>
            <div class="table">
              <el-table :data="tableData" style="width: 100%" v-loading="loading" height="280">
                <el-table-column label="文件名称">
                  <template #default="{ row }">
                    <el-input v-model="row.fileNickname" placeholder="请输入文件名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="上传文件">
                  <template #default="{ row, $index }">
                    <div class="upload">
                      <div class="file" v-if="row.realName">{{ row.realName }} <span @click="removeFile($index)" class="el-icon-error"></span></div>
                      <el-upload v-else style="color: #5eb2eb" :data="{ index: $index }" :http-request="uploadSectionFile" :show-file-list="false" action="https://jsonplaceholder.typicode.com/posts/">选择文件</el-upload>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="文档说明">
                  <template #default="{ row }">
                    <el-input v-model="row.docRemark" placeholder="请输入文档说明"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <div class="oper">
                      <span class="iconfont icon" @click="oper(scope, 1)">&#xe671;</span>
                      <span class="iconfont icon" @click="oper(scope, 2)">&#xe673;</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="line"></div>
            <div class="bar">
              <div class="bar-title"><span class="span"></span>设置文件共享方式</div>
            </div>
          </template>
          <div class="form">
            <div class="item" v-if="command != 2">
              <div class="label"><span class="span">*</span>文件名称</div>
              <el-input v-model="docData.fileNickname" @focus="onFocus" @blur="onBlur" placeholder="请输入文件名称"></el-input>
              <!-- <div class="error">文件名称已存在！</div> -->
            </div>
            <div class="item" v-if="command != 2">
              <div class="label"><span class="span">*</span>选择文件</div>
              <el-input v-model="docData.realName" placeholder="请选择要导入的文件" disabled></el-input>
              <el-upload :http-request="uploadSectionFile" :show-file-list="false" action="https://jsonplaceholder.typicode.com/posts/">
                <el-button>选择文件</el-button>
              </el-upload>
            </div>
            <div class="item">
              <div class="label"><span class="span">*</span>共享方式</div>
              <el-radio-group v-model="params.authType">
                <el-radio :label="0">公开</el-radio>
                <el-radio :label="1">按匹配密码方式共享</el-radio>
                <el-radio :label="2">按人员范围方式共享</el-radio>
                <el-radio :label="3">按部门进行分享</el-radio>
                <el-radio :label="4">私有</el-radio>
              </el-radio-group>
            </div>
            <div class="item" v-if="params.authType == 2 || params.authType == 3">
              <div class="label"><span class="span">*</span>选择范围</div>
              <!-- <el-button type="primary">选择范围</el-button> -->
              <select-range :isLow="true" :isNewLow="true" :selectedList.sync="selectedList" :authType="params.authType"></select-range>
            </div>
            <div class="item" v-if="params.authType == 1">
              <div class="label"><span class="span">*</span>输入密码</div>
              <el-input show-password v-model="params.sharePwd" placeholder="请输入密码"></el-input>
            </div>
            <div class="item" v-if="command != 2">
              <div class="label"><span class="span hidden1">*</span>文档说明</div>
              <el-input v-model="docData.docRemark" type="textarea" placeholder="请输入文档说明"></el-input>
            </div>
          </div>
        </div>
        <div class="footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="save" type="primary">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import SelectRange from "./SelectRange.vue";
export default {
  components: { SelectRange },
  props: {
    isDrawer: {
      type: Boolean,
      default: false,
    },
    command: {
      type: Number,
    },
    subId: {},
    editParams: {},
  },
  watch: {
    isDrawer: {
      handler(newVal) {
        if (!newVal) return;
        this.resetFiled();
      },
    },
  },
  data() {
    return {
      tableData: [],
      selectedList: [],
      docData: {},
      params: { authType: 0, sharePwd: "" },

      timerId: null, //用于防抖  多次触发上传
      fileList: [], //用于存储文件
      loading: false,

      editSubId: "",
    };
  },
  methods: {
    async onBlur() {
      await this.$api.documentManage.RegFileName({ dataId: this.command == 3 ? this.editSubId : this.subId[0], fileName: this.docData.fileNickname, sqlType: this.command == 3 ? 2 : 1, fileId: this.editParams.fileId || "" });
    },

    onFocus() {},

    async resetFiled() {
      //重置数据
      this.tableData = [], this.selectedList = [], this.docData = {}, this.params = { authType: 0, sharePwd: "" };
      this.timerId = null, this.fileList = [], this.loading = false;
      if (this.command !== 3) return;
      const { data } = await this.$api.documentManage.GetDocDetail(this.editParams);
      const {
        docRemark,
        fileUrl,
        fileName,
        fileSize,
        fileNickname,
        authExtendList,
        subId,
        docAuthModel: { authType, sharePwd },
      } = data.data;
      this.docData = { docRemark, fileUrl, realName: fileName, fileNickname, fileSize };
      this.params = { authType, sharePwd: sharePwd || "" };
      this.selectedList = authExtendList.map((i) => ({ id: i.dataId, name: i.dataName })) || [];
      this.editSubId = subId;
    },

    batchUpload(params) {
      //批量上传
      this.loading = true;
      const { file } = params;
      this.fileList.push(file);
      clearTimeout(this.timerId);
      this.timerId = setTimeout(async () => {
        const form = new FormData();
        this.fileList.map((i, idx) => {
          form.append(`formFileData${idx + 1}`, i);
        });
        const { data } = await this.$api.documentManage.NewUploadFile(form);
        this.tableData.push(...data.data.map((i) => ({ ...i, fileNickname: i.realName, docRemark: "" })));
        this.fileList = [];
        this.loading = false;
      }, 0);
    },

    beforeUpload(file) {
      const limitSize = 1024 * 1024 * 20; //超过20MB取消上传
      if (file.size > limitSize) {
        this.$message({ type: "warning", message: "文件大小不能超过20MB" });
        return false;
      }
      return true;
    },

    async save() {
      // 文件名称的唯一验证
      if (this.command !== 2) {
        // command  1新增  2批量新增  3编辑
        const { data: res } = await this.$api.documentManage.RegFileName({ dataId: this.command == 3 ? this.editSubId : this.subId[0], fileName: this.docData.fileNickname, sqlType: this.command == 3 ? 2 : 1, fileId: this.editParams.fileId || "" });
        if (res.status !== 200) return;
      } else if (this.command == 2) {
        // const flag = this.tableData.map(i => this.tableData.find(j => j.fileNickname === i.fileNickname)).some(i => i);
        // if (flag) return this.$message({ type: 'warning', message: '文件名称不可以相同' });
      }
      const authExtendList = this.selectedList.map((i) => ({ dataId: i.id, subId: i.companyId, dataName: i.name, isCheck: true, isDownload: true }));
      const postData = { subId: this.command == 3 ? this.editSubId : this.subId[0], docDataList: this.command != 2 ? [this.docData] : this.tableData, ...this.params, authExtendList, ...this.editParams };
      const { data } = await this.$api.documentManage[this.command != 3 ? "AddDocAuth" : "EditDocAuth"](postData);
      if (data.status == 200) {
        this.$emit("confirm");
        this.handleClose();
      }
    },

    removeFile(index) {
      const { realName, fileSize, fileUrl, fileNickname, docRemark } = this.tableData[index];
      this.tableData.splice(index, 1, { realName: "", fileSize: 0, fileUrl: "", fileNickname, docRemark });
    },

    async uploadSectionFile(params) {
      //导入
      this.loading = true;
      const { file, data: flag } = params;
      const form = new FormData();
      form.append("formFileData", file);
      console.log(params, file);
      const { data } = await this.$api.documentManage.NewUploadFile(form);
      const { realName, fileSize, fileUrl } = data.data[0];
      if (this.command != 2) {
        // 1新增文档  2批量新增文档
        this.docData = Object.assign({}, this.docData, { realName, fileSize, fileUrl });
        this.loading = false;
        return;
      }
      if (flag) {
        //表格单行上传
        const { fileNickname, docRemark } = this.tableData[flag.index];
        this.tableData.splice(flag.index, 1, { realName, fileSize, fileUrl, fileNickname, docRemark });
      }
      this.loading = false;
    },

    oper({ row, $index }, type) {
      if (type == 1) {
        //添加
        this.tableData.splice($index + 1, 0, { realName: "", fileSize: 0, fileUrl: "", fileNickname: "", docRemark: "" });
      }
      if (type == 2) {
        //删除
        this.tableData.splice($index, 1);
      }
    },

    handleClose(flag) {
      if (flag === 1) return;
      this.$emit("update:isDrawer", false);
    },
  },
};
</script>

<style lang="less" scoped>
.comp-add-document {
  .drawer-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    .header {
      padding: 10px 20px;
      display: flex;
      align-items: center;
      background: #f4f9fe;
      justify-content: space-between;
      .title {
      }
      .close {
        display: inline-block;
        font-size: 20px;
        cursor: pointer;
      }
    }
    .section {
      flex: 1;
      overflow: auto;
      .bar {
        padding: 0 20px;
        margin: 10px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .bar-title {
          display: flex;
          align-items: center;
          font-weight: bold;
          // font-size: 14px;
          .span {
            display: inline-block;
            width: 3px;
            height: 18px;
            background: #62b3e8;
            border-radius: 3px;
            margin-right: 8px;
          }
        }
      }
      .table {
        padding: 0 20px;
        padding-bottom: 20px;
        .el-upload {
          color: #62b3e8;
        }
        .oper {
          .icon {
            font-size: 20px;
            cursor: pointer;
            display: inline-block;
            margin-right: 15px;
          }
        }
      }
      .line {
        width: 100%;
        height: 10px;
        background: #f6f6f6;
      }
      .form {
        padding: 0 20px;
        margin-top: 20px;
        .item {
          display: flex;
          text-align: left;
          margin-bottom: 20px;
          position: relative;
          .error {
            position: absolute;
            font-size: 12px;
            color: red;
          }
          .label {
            width: 100px;

            color: #8e97ad;
            .span {
              color: red;
            }
            .hidden1 {
              visibility: hidden;
            }
          }
          .el-radio {
            display: block;
            margin-top: 3px;
            margin-bottom: 8px;
          }
        }
      }
    }
    .footer {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}
</style>
